package com.gaohc.system.sysuser;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gaohc.common.annotation.Log;
import com.gaohc.common.constant.UserConstants;
import com.gaohc.common.core.domain.AjaxJson;
import com.gaohc.common.core.domain.entity.SysRole;
import com.gaohc.common.core.domain.entity.SysUser;
import com.gaohc.common.enums.BusinessType;
import com.gaohc.common.exception.BusinessException;
import com.gaohc.common.utils.StringUtils;
import com.gaohc.system.sysuser.ISysRoleService;
import com.gaohc.system.sysuser.ISysUserRoleService;
import com.gaohc.system.sysuser.ISysUserService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@SaCheckLogin
@RestController
@RequestMapping("/system/user")
public class SysUserController
{
    @Resource
    private ISysUserService userService;
    @Resource
    private ISysRoleService roleService;
    @Resource
    private ISysUserRoleService userRoleService;


    /**
     * 获取用户列表
     */
    @SaCheckPermission("system:user:list")
    @GetMapping("/list")
    public AjaxJson list(SysUser user)
    {
        Page<SysUser> sysUserPage = new Page<>();
        userService.lambdaQuery()
                .like(StringUtils.isNotEmpty(user.getUserName()), SysUser::getUserName, user.getUserName())
                .like(StringUtils.isNotEmpty(user.getPhonenumber()), SysUser::getPhonenumber, user.getPhonenumber())
                .eq(StringUtils.isNotEmpty(user.getStatus()), SysUser::getStatus, user.getStatus())
                .ge(StringUtils.isNotEmpty(user.getBeginTime()), SysUser::getCreateTime, user.getBeginTime())
                .le(StringUtils.isNotEmpty(user.getEndTime()), SysUser::getCreateTime, user.getEndTime())
                .page(sysUserPage);
        return AjaxJson.getSuccessData(sysUserPage);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @SaCheckPermission("system:user:query")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxJson getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        Map<String, Object> result = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        result.put("roles", roles);
        if (StringUtils.isNotNull(userId))
        {
            result.put("data", userService.getById(userId));
            result.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return AjaxJson.getSuccessData(result);
    }

    /**
     * 重置密码
     */
    @SaCheckPermission("system:user:resetPwd")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxJson resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        SysUser sysUser = new SysUser();
        sysUser.setUserId(user.getUserId());
        sysUser.setPassword(user.getPassword());
        userService.updateById(user);
        return AjaxJson.getSuccess();
    }

    /**
     * 状态修改
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxJson changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        SysUser sysUser = userService.getUserInfoById(user.getUserId());
        if (sysUser == null) {
            throw new BusinessException("用户不存在");
        }
        SysUser newUser = new SysUser();
        newUser.setUserId(user.getUserId());
        newUser.setStatus(user.getStatus());
        userService.updateById(newUser);
        return AjaxJson.getSuccess();
    }

    /**
     * 新增用户
     */
    @SaCheckPermission("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxJson add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName())))
        {
            return AjaxJson.getError("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxJson.getError("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxJson.getError("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        userService.insertUser(user);
        return AjaxJson.getSuccess();
    }

    /**
     * 删除用户
     */
    @SaCheckPermission("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxJson remove(@PathVariable Long[] userIds)
    {
        Long loginId = Long.parseLong(StpUtil.getLoginId().toString());
        if (ArrayUtils.contains(userIds, loginId))
        {
            throw new BusinessException("当前用户不能删除");
        }
        // 删除用户
        userService.removeByIds(Arrays.asList(userIds));
        // 删除用户-角色关联
        userRoleService.removeByIds(Arrays.asList(userIds));
        return AjaxJson.getSuccess();
    }

    /**
     * 根据用户编号获取授权角色
     */
    @SaCheckPermission("system:user:query")
    @GetMapping("/authRole/{userId}")
    public AjaxJson authRole(@PathVariable("userId") Long userId)
    {
        Map<String, Object> ajax = new HashMap<>();
        SysUser user = userService.getUserInfoById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !SysUser.isAdmin(userId)).collect(Collectors.toList()));
        return AjaxJson.getSuccessData(ajax);
    }

    /**
     * 修改用户
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxJson edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            throw new BusinessException("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            throw new BusinessException("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        userService.updateUser(user);
        return AjaxJson.getSuccess();
    }


    /**
     * 用户授权角色
     */
    @SaCheckPermission("system:user:query")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxJson insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.insertUserAuth(userId, roleIds);
        return AjaxJson.getSuccess("授权成功");
    }

}
